module.exports = {
  /**
   * 获取班级
   */
  async getClasses(req) {
    const { searchField, searchValue } = req.query;
    let countParams = {};
    if (searchField && searchValue) {
      countParams = {
        searchField,
        searchValue,
      };
    }
    const count = await req.classesModel.getClassesCount(countParams);
    const result = await req.classesModel.getClasses(req.query);
    return {
      count,
      result,
    };
  },
  /**
   * 添加
   */
  async addClass(req, { boom }) {
    const { classname } = req.payload;

    const classnameExist = await req.classesModel.isExist(
      "classname",
      classname
    );
    if (classnameExist) {
      return boom.badRequest("班级名已存在");
    }
    const result = await req.classesModel.addClasses(req.payload);
    return result;
  },

  /**
   * 根据ID获取单个班级信息
   */
  async getClassById(req) {
    const result = await req.classesModel.getClassById(req.params.id);
    return result;
  },

  /**
   * 根据ID删除班级
   */
  async deleteClassById(req) {
    await req.classesModel.deleteClassById(req.params.id);
    return {};
  },

  /**
   * 根据多个ID批量删除班级
   */
  async deleteClassesByIds(req) {
    await req.classesModel.deleteClassesByIds(req.payload.ids);
    return {};
  },

  /**
   * 根据ID更新班级信息
   */
  async updateClassById(req, { boom }) {
    const { classname } = req.payload;
    const cls = await req.classesModel.getClassById(req.params.id);
    if (cls.classname !== classname) {
      const classnameExist = await req.classesModel.isExist(
        "classname",
        classname
      );
      if (classnameExist) {
        return boom.badRequest("班级名已存在");
      }
    }
    await req.classesModel.updateClassById(req.params.id, req.payload);
    return {};
  },

  /**
   * 判断字段值是否存在
   */
  async isExist(req) {
    const { field, value } = req.query;
    const result = await req.classesModel.isExist(field, value);
    return Boolean(result);
  },
};
